package edu.univercidade.tcc.server.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.scheduling.annotation.Async;

import ca.digitalface.jasperoo.RooJasperoo;
import edu.univercidade.tcc.server.validator.ProjectAllowsChosenIssueTracker;

@RooJavaBean
@RooToString
@RooJasperoo
@RooEntity(finders = { "findIssuesByProjectAndAssignedTo", "findIssuesById",
		"findIssuesByProjectAndAssignedToAndIssueStatus" })
@ProjectAllowsChosenIssueTracker
public class Issue {

	@Column(name = "created_on", nullable = false)
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Date createdOn;

	@Size(max = 4096)
	private String description;

	@NotNull
	@Column(name = "due_date")
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Date dueDate;

	@Column(name = "estimated_hours")
	private Integer estimatedHours;

	@Column(name = "start_date")
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Date startDate;

	@NotNull
	@NotBlank
	@Size(max = 255)
	private String subject;

	@Column(name = "updated_on")
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "SS")
	private Date updatedOn;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "tracker_id")
	private Tracker tracker;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "project_id")
	private Project project;

	@ManyToOne
	@JoinColumn(name = "status_id")
	private IssueStatus issueStatus;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "assigned_to_id")
	private ProjectMember assignedTo;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "priority_id")
	private Priority priority;

	@ManyToOne(optional = false)
	@JoinColumn(name = "author_id")
	private ProjectMember author;

	@ManyToOne
	@JoinColumn(name = "parent_id")
	private edu.univercidade.tcc.server.model.Issue parent;

	@Autowired
	@Transient
	private transient MailSender mailTemplate;

	@Autowired
	@Transient
	private transient SimpleMailMessage simpleMailMessage;

	@Async
	public void sendMessage(String mailTo, String subject, String message) {
		simpleMailMessage.setTo(mailTo);
		simpleMailMessage.setSubject(subject);
		simpleMailMessage.setText(message);
		mailTemplate.send(simpleMailMessage);
	}
}
